package org.rainbow.password;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyRealm extends AuthorizingRealm {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        
        String username = (String)token.getPrincipal(); //得到用户名
		//String password = new String((char[])token.getCredentials()); //得到密码
        
        //String username = "rainbow"; //用户名及salt1
    	//从数据库等数据源获得 盐和加密后的密码
        String salt = "0159053f4504827fbd9f42d99c22a7aa";
        String password = "80d587eda085a1cf86007f6a2867ff4c"; //加密后的密码
		
		logger.debug("password===============>" + password);
		
		//查看源码 CredentialsMatcher 中 doCredentialsMatch
		//SimpleAuthenticationInfo 的password 已经是传入加密后的
        SimpleAuthenticationInfo ai = new SimpleAuthenticationInfo(username, password, getName());
        ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt)); //盐是用户名+随机数
        return ai;
    }

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO 自动生成的方法存根
		return null;
	}
}
